<script lang="ts" setup>
	import {
		reactive,
		toRefs,
		ref,
		onMounted
	} from 'vue'

	interface Props {
		url : string // 背景图地址
		height : string // 默认高度
		step : number //步长
		top : number// 顶部距离
	}

	const props = defineProps<Props>()

	// 当前页面元素
	const reference = ref()

	const state = reactive({
		url: '',
		height: '',
		step: 0,
		top: 0,
		backgroundSize: 100,
		paddingTop: props.top,
		baseRate: 100,
		clientMoveY: 0,
		scrollTop: 0,
		timer: null
	})

	const {
		backgroundSize,
		paddingTop,
		height,
		step,
		top,
		url
	} = toRefs(state)


	// 监听移动
	const touchmove = e => {
		const touchData = e.changedTouches[0]
		const {
			clientY
		} = touchData
		// 判断下拉
		if (state.clientMoveY - clientY < 0) {
			state.baseRate = state.baseRate + step.value
			state.backgroundSize = state.baseRate
			state.paddingTop = top.value * (state.baseRate / 100)
		}
		state.clientMoveY = clientY
	}

	// 监听移动结束
	const touchend = () => {
		// 页面不在顶部不调用
		if (state.scrollTop !== 0) {
			return
		}
		state.timer && clearInterval(state.timer)
		// 回弹
		state.timer = setInterval(() => {
			state.baseRate = state.baseRate - step.value * 2
			if (state.baseRate <= 100) {
				state.baseRate = 100
				state.paddingTop = top.value
				clearInterval(state.timer)
			}
			state.backgroundSize = state.baseRate
			state.paddingTop = top.value * (state.baseRate / 100)
		}, 10)
	}



	onMounted(() => {

		state.url = props.url ?? 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fc5f6153c-589f-4b46-a371-705652eeb8ec%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1707988800&t=f31af2fe85d5b4be4a23c06721935851'
		state.height = props.height ?? '360rpx'
		state.step = props.step ?? 2
		state.top = props.top ?? 180

	})
</script>
<template>
	<view ref="reference" class="background_box" :style="{
		height:height,
		backgroundImage:`url(${url})`,
		 backgroundSize: `${backgroundSize}% auto`,
		      paddingTop: paddingTop + 'px'
	}" @touchend="touchend" @touchmove="touchmove">


	</view>
</template>
<style scoped>
	.background_box {
		width: 100%;
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
	}
</style>